/*
 * MessageQueueLauncher.h
 *
 *  Created on: 09/12/2013
 *      Author: gonzalo
 */

#ifndef MESSAGEQUEUELAUNCHER_H_
#define MESSAGEQUEUELAUNCHER_H_

#include "../../IPC/MessageQueue.h"
#include "../../common/IPCUids.h"
#include <sys/stat.h>

namespace middleware {

class DistributedIPCLauncher {
public:
	DistributedIPCLauncher();

	/*
	 * Param consumer is when it's a process that is reading from the queue
	 */
	template<typename T>
	static void createMQueue( std::string file, int charKey, bool consumer, std::string nombreaAgenteDestino = "", long mtype = 0, int size = 0);

	template<typename T>
	static void destroyMQueue( std::string file, int charKey );

	template<typename T>
	static void createShMem( std::string file, int charKey);

	template<typename T>
	static void destroyShMem( std::string file, int charKey );

	template<typename T>
	static void createSem( std::string file, int charKey);

	template<typename T>
	static void destroySem ( std::string file, int charKey );

	virtual ~DistributedIPCLauncher();
};

template<typename T>
static void createMQueue( std::string file, int charKey, bool consumer, std::string nombreaAgenteDestino, long mtype, int size) {
	/* Esto es concurrente */
	ipc::MessageQueue<T>::create(file, charKey);

	/* Esto es distribuido */
	if(fork() == 0) {
		if (consumer)
			execl("../../out/receptorServicioMQ", "receptorServicioMQ", NULL);
		else
			execl("../../out/emisorServicioMQ",
					"emisorServicioMQ",
					nombreaAgenteDestino,
					StringUtils::itos(IPCUids::getUid(file, charKey)),
					StringUtils::itos(mtype),
					StringUtils::itos(size),
					NULL
			);
	}
}

template<typename T>
static void destroyMQueue( std::string file, int charKey ) {
	ipc::MessageQueue<T>::destroy(file, charKey);
	// Ver si hace falta algo más
}

template<typename T>
static void createShMem( std::string file, int charKey) {

}

template<typename T>
static void destroyShMem( std::string file, int charKey ) {

}

template<typename T>
static void createSem( std::string file, int charKey) {

}

template<typename T>
static void destroySem ( std::string file, int charKey ) {

}

} /* namespace middleware */
#endif /* MESSAGEQUEUELAUNCHER_H_ */
